package cn.edu.lzu.service.impl;

import cn.edu.lzu.common.assist.DataPage;
import cn.edu.lzu.common.assist.ResponseResult;
import cn.edu.lzu.common.util.Email;
import cn.edu.lzu.dao.ExaminerMapper;
import cn.edu.lzu.dao.RoleMapper;
import cn.edu.lzu.entity.Examiner;
import cn.edu.lzu.entity.Role;
import cn.edu.lzu.service.ExaminerService;
import com.sun.xml.internal.messaging.saaj.packaging.mime.MessagingException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

/**
 * @PackageName: cn.edu.lzu.service.impl
 * @ClassName: ExaminerServiceImpl
 * @Description: TODO
 * @Author: 张琦[QQ:3098086691]
 * @Date: 2019/11/28 17:05
 * @Version: 1.0
 */
@Service
@Transactional
public class ExaminerServiceImpl implements ExaminerService {
    @Resource
    private ExaminerMapper examinerMapper;
    @Resource
    private RoleMapper roleMapper;

    @Override
    public Examiner selectExaminerById(long examinerId) {
        Examiner examiner=examinerMapper.selExaminerById(examinerId);
        return examiner;
    }

    @Override
    public int updateExaminerLastLoginTime(long examinerId) {
        return examinerMapper.updExaminerLastLoginTime(examinerId);
    }

    @Override
    public DataPage selectExaminerPage(int currentPageNum, int pageSize, long unitId) {
        //新的一页开始下标
        int startIndex=(currentPageNum-1)*pageSize;
        //一页数据
        List<Examiner> examinerList=examinerMapper.selPageExaminer(startIndex, pageSize, unitId);
        //该单位的员工总数
        int totalExamiers=examinerMapper.selCountOfUnit(unitId);
        DataPage examinerPage=new DataPage();
        examinerPage.setData(examinerList);
        examinerPage.setCode(0);
        examinerPage.setMsg("成功");
        examinerPage.setTotalCount(totalExamiers);
        return examinerPage;
    }

    /**
     * @Author: 张琦[QQ:3098086691]
     * @Description: TODO 更新examinerId员工的status状态，以responseResult返回结果
     * @Date: 2019/12/2 11:45
     * @Param: [examinerId, status]
     * @Return: cn.edu.lzu.common.assist.ResponseResult
     **/
    @Override
    public ResponseResult updateExaminerStatus(long examinerId, boolean status) {
        int result=examinerMapper.updExaminerStatus(examinerId, status);
        ResponseResult responseResult=new ResponseResult();
        String msg="";
        if(status)
            msg=msg+"启用";
        else
            msg=msg+"禁用";
        if(result==1){
            responseResult.setCode(1);
            responseResult.setMsg(msg+"成功");
        }else{
            responseResult.setCode(0);
            responseResult.setMsg(msg+"失败");
        }
        return responseResult;
    }

    /**
     * @Author: 张琦[QQ:3098086691]
     * @Description: TODO 注册新员工：获取本单位的当前最大员工编号，拿到后六位，加一，然后补全六位在和单位id拼接形成新的员工号；初始密码为出生年月
     * @Date: 2019/12/4 11:23
     * @Param: [examiner]
     * @Return: cn.edu.lzu.common.assist.ResponseResult
     **/
    @Override
    public ResponseResult registeExaminer(Examiner examiner) {
        System.out.println("examiner:"+examiner);
        //获取目前本单位最大的员工编号
        long maxExaminerId=examinerMapper.selMaxExaminerIdOfUnit(examiner.getUnitId());
        //最大员工号后六位+1然后与单位代码拼接形成新的员工号,如果不够6位数，就在前面补0
        String examinerIdLast=(Long.valueOf((maxExaminerId+"").substring(6, 12))+1)+"";
        while (examinerIdLast.length()<6){
            examinerIdLast="0"+examinerIdLast;
        }
        examiner.setExaminerId(Long.valueOf(examiner.getUnitId()+examinerIdLast));
        //设置新员工号的密码：生日的年份+月份
        examiner.setPassword(examiner.getIdNumber().substring(6, 12));
        //设置注册时间
        examiner.setRegisteTime(new Timestamp(System.currentTimeMillis()));
        int result=examinerMapper.insNewExaminer(examiner);
        ResponseResult responseResult=new ResponseResult();
        if(result==1){
            responseResult.setMsg("注册成功");
            responseResult.setCode(1);
        }else{
            responseResult.setCode(0);
            responseResult.setMsg("注册失败");
        }
        return responseResult;
    }

    /**
     * @Author: 张琦[QQ:3098086691]
     * @Description: TODO 批量设置status为true，即设置为启用状态
     * @Date: 2019/12/4 11:26
     * @Param: [examinerIds, unitId]
     * @Return: cn.edu.lzu.common.assist.ResponseResult
     **/
    @Override
    public ResponseResult batchEnabledExaminers(String examinerIds) {
        examinerIds=examinerIds.substring(0, examinerIds.length()-1);
        int result=examinerMapper.updBatchExaminerStatusToTrue(examinerIds);
        ResponseResult responseResult=new ResponseResult();
        if(result==(examinerIds.split(",")).length){
            responseResult.setCode(1);
            responseResult.setMsg("批量启用成功");
        }else{
            responseResult.setCode(0);
            responseResult.setMsg("批量启用失败");
        }
        return responseResult;
    }

    /**
     * @Author: 张琦[QQ:3098086691]
     * @Description: TODO 批量设置status为false，即设置为禁用状态
     * @Date: 2019/12/4 14:19
     * @Param: [examinerIds, unitId]
     * @Return: cn.edu.lzu.common.assist.ResponseResult
     **/
    @Override
    public ResponseResult batchDisenabledExaminers(String examinerIds, long examinerSelfId) {
        ResponseResult responseResult=new ResponseResult();
        examinerIds=examinerIds.substring(0, examinerIds.length()-1);
        //如果禁用的账号中包括本人的账号，则禁用失败
        for(String examinerIdStr:examinerIds.split(",")){
            if(Long.valueOf(examinerIdStr)==examinerSelfId){
                responseResult.setCode(0);
                responseResult.setMsg("批量禁用失败：不能禁用自己的账号");
                return responseResult;
            }
        }
        int result=examinerMapper.updBatchExaminerStatusToFalse(examinerIds);
        if(result==(examinerIds.split(",")).length){
            responseResult.setCode(1);
            responseResult.setMsg("批量禁用成功");
        }else{
            responseResult.setCode(0);
            responseResult.setMsg("批量禁用失败");
        }
        return responseResult;
    }

    @Override
    public ResponseResult batchDeleteExaminers(String examinerIds, long examinerSelfId) {
        ResponseResult responseResult=new ResponseResult();
        examinerIds=examinerIds.substring(0, examinerIds.length()-1);
        //如果删除的账号中包括本人的账号，则删除失败
        for(String examinerIdStr:examinerIds.split(",")){
            if(Long.valueOf(examinerIdStr)==examinerSelfId){
                responseResult.setCode(0);
                responseResult.setMsg("批量删除失败：不能删除自己的账号");
                return responseResult;
            }
        }
        int result=examinerMapper.updBatchDeleteExaminers(examinerIds);
        if(result==(examinerIds.split(",")).length){
            responseResult.setCode(1);
            responseResult.setMsg("批量删除成功");
        }else{
            responseResult.setCode(0);
            responseResult.setMsg("批量删除失败");
        }
        return responseResult;
    }

    /**
     * @Author: 张琦[QQ:3098086691]
     * @Description: TODO 根据examinerId删除账号
     * @Date: 2019/12/4 16:56
     * @Param: [examinerId, examinerSelfId]
     * @Return: cn.edu.lzu.common.assist.ResponseResult
     **/
    @Override
    public ResponseResult deleteExaminerByExaminerId(long examinerId, long examinerSelfId) {
        ResponseResult responseResult=new ResponseResult();
        //如果examinerId是当前‘操作员’的账号，则删除失败
        if(examinerId==examinerSelfId){
            responseResult.setCode(0);
            responseResult.setMsg("删除失败：不能删除自己的账号");
            return responseResult;
        }
        int result=examinerMapper.updDeleteExaminerByExaminerId(examinerId);
        if(result==1){
            responseResult.setCode(1);
            responseResult.setMsg("删除成功");
            return responseResult;
        }else {
            responseResult.setCode(0);
            responseResult.setMsg("删除失败");
            return responseResult;
        }
    }

    /**
     * @Author: 张琦[QQ:3098086691]
     * @Description: TODO 根据输入的examinerId进行模糊搜索：如果输入为空，就从头搜索出一页本单位的数据
     * @Date: 2019/12/5 15:33
     * @Param: [unitId, inputExaminerId, pageSize]
     * @Return: cn.edu.lzu.common.assist.DataPage
     **/
    @Override
    public DataPage fuzzySearchByExaminerId(long unitId, String inputExaminerId, int pageSize) {
        List<Examiner> examinerList=null;
        int totalCount=0;
        //获取输入的字符串最开始的连续数字序列
        String examinerId="";
        for(int i=0; i<inputExaminerId.length(); i++){
            char num=inputExaminerId.charAt(i);
            if(48<=num && num<=57){
                examinerId=examinerId+num;
            }else{
                break;
            }
        }
        DataPage examinerPage=new DataPage();
        if(examinerId.length()!=0){
            examinerList=examinerMapper.selFuzzySearchExaminersByExaminerId(unitId, pageSize, examinerId);
            totalCount=examinerMapper.selCountExaminerByFuzzySearch(unitId, examinerId);
        }else{
            examinerList=examinerMapper.selPageExaminer(0, pageSize, unitId);
            totalCount=examinerMapper.selCountOfUnit(unitId);
        }
        examinerPage.setData(examinerList);
        examinerPage.setMsg("搜索成功");
        examinerPage.setCode(0);
        examinerPage.setTotalCount(totalCount);
        return examinerPage;
    }

    /**
     * @Author: 张琦[QQ:3098086691]
     * @Description: TODO 修改密码
     * @Date: 2019/12/5 21:52
     * @Param: [newPassword, examinerId]
     * @Return: cn.edu.lzu.common.assist.ResponseResult
     **/
    @Override
    public ResponseResult updateSelfPassword(String newPassword, long examinerId) {
        int result=examinerMapper.updPassowrdByExaminerId(newPassword, examinerId);
        ResponseResult responseResult=new ResponseResult();
        if(result==1){
            responseResult.setCode(1);
            responseResult.setMsg("密码修改成功，请重新登录！");
        }else{
            responseResult.setCode(0);
            responseResult.setMsg("密码修改失败");
        }
        return responseResult;
    }

    @Override
    public ResponseResult findPwd(String examinerName, String idNumber, String email) {
        Examiner examiner=examinerMapper.selUserByIdNumberAndName(examinerName, idNumber);
        ResponseResult responseResult=new ResponseResult();
        if(examiner==null){
            responseResult.setCode(0);
            responseResult.setMsg("没有该用户信息！");
        }else{
            try {
                Email.sendEmail(email, "找回密码",  "你的账号为："+examiner.getExaminerId()+" 您的密码为："+examiner.getPassword()+" 【滕飞健康】");
                responseResult.setCode(1);
                responseResult.setMsg("密码找回成功！");
            } catch (MessagingException e) {
                responseResult.setCode(0);
                responseResult.setMsg("密码找回失败！");
                e.printStackTrace();
            } catch (javax.mail.MessagingException e) {
                responseResult.setCode(0);
                responseResult.setMsg("密码找回失败！");
                e.printStackTrace();
            }
        }
        return responseResult;
    }

    @Override
    public DataPage getExaminers(Examiner examiner) {
        List<Examiner> examienrList=examinerMapper.selExaminersByUnitId(examiner.getUnitId());
        DataPage dataPage=new DataPage();
        dataPage.setData(examienrList);
        dataPage.setCode(0);
        dataPage.setTotalCount(examienrList.size());
        return dataPage;
    }


}
